#include "widget.h"
#include "ui_widget.h"
#include <QScreen>
#include <QVBoxLayout>
#include <QImage>
#include <QPainter>

const QString ip = "43.140.248.105";
const quint16 port = 8888;

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);

   setWindowFlag(Qt::FramelessWindowHint);

   // 网络通信
   tcpclient = new TcpService(this);
   if(!tcpclient->connectToServer(ip, port))
   {
       // 这里要加载一个网络连接错误的页面
       tcpclient->errorString();

   }
   udpclient = new UdpService(this);

   // 各个场景
   login_scene = new Login(this);
   userregister_scene = new UserRegister(this);
   menu_scene = new MenuScene(this);

   // 场景对应的处理模型
   login_view_model = new LoginViewModel(this, tcpclient);
   register_view_model = new RegisterViewModel(this, tcpclient);

   // 各个场景的信号处理
   connect(login_scene, &Login::closeWindow, this, &Widget::close);
   connect(login_scene, &Login::login, login_view_model, &LoginViewModel::loginRequest);
   connect(login_scene, &Login::userRegister, this, [this](){
       disconnect(tcpclient, &TcpService::messageReceived, login_view_model, &LoginViewModel::respHandle);
       this->stackedWidget->setCurrentIndex(2);
       connect(tcpclient, &TcpService::messageReceived, register_view_model, &RegisterViewModel::respHandle);
       centerWindow();
   });

   connect(userregister_scene, &UserRegister::goBack, this, [this](){
       disconnect(tcpclient, &TcpService::messageReceived, register_view_model, &RegisterViewModel::respHandle);
       this->stackedWidget->setCurrentIndex(0);

       connect(tcpclient, &TcpService::messageReceived, login_view_model, &LoginViewModel::respHandle);
       centerWindow();
   });
   connect(userregister_scene, &UserRegister::closeWindow, this, &Widget::close);
   connect(userregister_scene, &UserRegister::commit, register_view_model, &RegisterViewModel::registerRequest);


   // 将场景都添加到场景管理器中
   stackedWidget = new QStackedWidget(this);
   stackedWidget->addWidget(login_scene);
   stackedWidget->addWidget(menu_scene);
   stackedWidget->addWidget(userregister_scene);
   stackedWidget->setCurrentIndex(0);
   centerWindow();

   // 添加布局管理器
   QVBoxLayout *layout = new QVBoxLayout(this);
   layout->addWidget(stackedWidget);
   layout->setContentsMargins(0, 0, 0, 0); // 去除边距
}

Widget::~Widget()
{
    delete ui;
}

void Widget::centerWindow()
{
    QScreen *screen = QGuiApplication::primaryScreen();
    QRect screenGeometry = screen->geometry();
    move(screenGeometry.center() - rect().center());
}



